<template>
  <div class="maina">
    <arrow :topList="topList"></arrow>
    <div>
      <div class="content">
        <article class="content_box">
          <div class="title_left">内容管理 > 我的初稿</div>
          <div class="app-container">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="100px">
              <el-form-item label="关键词：" style="margin-left: -45px;" prop="keyword">
                <el-input v-model="queryParams.keyWords" placeholder="请输入关键词" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="初稿状态：" prop="type">
                <el-select v-model="queryParams.articleExamineState" placeholder="请选择初稿状态">
                  <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8" style="margin-left: -25px;">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table stripe v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="内容编号" width="170" prop="topicXh" />
              <!-- <el-table-column label="展示编号" align="center" prop="topicXh" /> -->
              <el-table-column label="内容名称" align="center" prop="title" />
              <el-table-column label="内容目标" align="center" prop="target" />
              <el-table-column label="课题开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="内容类型" align="center" prop="type" />
              <el-table-column label="内容状态" align="center" prop="articleExamineState" />
              <el-table-column label="是否原创" align="center" prop="copyrightType" />
              <el-table-column label="审核人" align="center" prop="actualExamineUserid" />
              <el-table-column label="审核意见" align="center" prop="examineFailedReason">
                <template slot-scope="scope">
                  <!-- 小于12位默认展示 -->
                  <div v-if="scope.row.examineFailedReason && scope.row.examineFailedReason.length <= 8">{{
      scope.row.examineFailedReason }}</div>
                  <!-- 大于12为只展示12位 -->
                  <el-tooltip style="cursor: pointer;"
                    v-if="scope.row.examineFailedReason && scope.row.examineFailedReason.length > 8"
                    popper-class="testtooltip" :content="scope.row.examineFailedReason" placement="top-start">
                    <div v-if="scope.row.examineFailedReason">{{ scope.row.examineFailedReason.slice(0, 8) + '...' }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <div>
                    <p style="display: flex;">
                      <el-button plain size="small" icon="el-icon-search" @click="preview(scope.row)">预览</el-button>
                      <el-button size="small" plain type="danger" icon="el-icon-delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                    </p>
                    <p style="display: flex;">
                      <el-button type="success" plain icon="el-icon-edit" size="small" @click="handleUpdate(scope.row)"
                        v-if="['待审核', '审核未通过', '拒绝审核', '审核通过'].includes(scope.row.articleExamineState)">修改</el-button>
                      <el-button plain type="info" size="small" icon="el-icon-edit" @click="handleExam(scope.row)"
                        v-if="['待审核', '审核未通过', '拒绝审核'].includes(scope.row.articleExamineState)">提审</el-button>
                    </p>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>

          <el-dialog :title="title" stripe :visible.sync="openTiShen" width="500px" append-to-body>
            <div style="height: 600px;">
              <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane label="指定审核" name="first">
                  <el-form ref="form" :model="pop" label-width="80px">
                    <el-col :span="24">
                      <el-form-item label="审核设定">
                        <el-select v-model="pop.title" placeholder="请选择" style="padding-left: 30px;">
                          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="搜索" label-width="80px" >
                        <el-input style="width: 245px;padding-left: 30px" v-model="pop.search" placeholder="请输入昵称"></el-input>
                        <el-button type="primary" @click="proSearch" style="margin-left: 20px;">查询</el-button>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="10">
                      <el-button type="primary" @click="proSearch">查询</el-button>
                    </el-col> -->
                  </el-form>
                  <div style="padding-left: 15px;">
                    <el-table height="350" @row-click="rowSelect" :data="tableData" style="width: 100%">
                      <el-table-column prop="id" label="用户ID" width="180">
                      </el-table-column>
                      <el-table-column prop="name" label="昵称" width="180">
                      </el-table-column>
                      <el-table-column prop="doc" label="专家认证">
                      </el-table-column>
                    </el-table>
                  </div>
                  <!-- <div style="padding-left: 240px;padding-top: 30px;">
                  <el-col :span="5">
                    <el-button type="primary">选择</el-button>
                  </el-col>
                  <el-col :span="5">
                    <el-button type="info" plain>取消</el-button>
                  </el-col>
                </div> -->
                  <div style="text-align: center;padding-top: 30px;">
                    <el-button type="primary" @click="submitData('zhiding')">提交审核</el-button>
                  </div>
                </el-tab-pane>


                <!-- <el-tab-pane label="邀请审核" name="second">
                <el-form ref="invationForm" :model="invation" :rules="rules" label-width="140px">
                  <el-col :span="12">
                    <el-form-item label="被邀请人姓名：" prop="name">
                      <el-input style="width: 220px;" v-model="invation.name" placeholder="被邀请人姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="被邀请人电话：" prop="phone">
                      <el-input style="width: 220px;" v-model="invation.phone" placeholder="被邀请人电话"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="被邀请人职称：" prop="job">
                      <el-select v-model="invation.job" placeholder="请选择医生职称">
                        <el-option v-for="dict in dict.type.user_auth_doctor_rank" :key="dict.value" :label="dict.label"
                          :value="dict.value">
                        </el-option>
                      </el-select>
                    
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" style="margin-left: 10px;">
                    <el-button type="primary" style="margin-right: 10px;">生成邀请链接</el-button>
                    <p>{{ invation.url }}</p>
                  </el-col>
                  <el-col  style="margin-top: 20px;">
                      <div><el-button style="margin-left: 10px;" type="primary" @click="makeQr">生成邀请二维码</el-button></div>
                      <div ref="qrimg" id="qrimg" style="width: 200px;height: 200px;"></div>
                    <div style="padding-top: 20px;text-align: center;">温馨提示：被邀请人支撑需要高于创作者职称</div>
                    <div style="text-align: center;padding-top: 30px;padding-left: 40px;">
                      <el-button type="primary" @click="submitData('yaoqing')">提交审核</el-button>
                    </div>
                  </el-col>
                </el-form>
              </el-tab-pane>
 -->


                <el-tab-pane label="内容免审" name="third">
                  <h2 style="text-align: center;margin-top: 100px;">已选定内容免审，免审可直接发布</h2>
                  <div style="text-align:  center;padding-top: 330px;">
                    <el-button type="primary" @click="submitData('free')">提交审核</el-button>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-dialog>
          <shenheView :preOpen="preOpen" :myRow="myRow" :isForm="false" @updatePre="updatePre"></shenheView>
        </article>
      </div>
    </div>
  </div>
</template>

<script>
import arrow from '@/views/components/arrow'
import shenheView from '@/views/components/shenheview'
import { listTopic, delMytopicChuGao } from '@/api/my/xuanti'
import { chugaoList, getAuditStaff, submitArticleAudit, generateArticleQR, ArticlePreview } from '@/api/my'

export default {
  components: { arrow, shenheView },
  name: '',
  dicts: ['article_topic_schedule'],
  data() {
    return {
      myRow: {},
      invation: {
        name: '',  //邀请人姓名
        phone: '',
        job: '',
        url: ''
      },
      pop: {
        title: '',  //所选专家
        search: '', //搜索专家
      },
      activeName: 'first',
      options: [{
        value: '',
        label: ''
      }],
      value: '',
      openTiShen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章选题表格数据
      topicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      preOpen: false,   //预览dialog开关
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWords: null,
        articleExamineState: null,
        topicXh: null,
      },
      processList: [
        { value: 1, label: '素材归集中' },
        { value: 2, label: '内容创作中' },
        { value: 3, label: '创作已完成' },
        { value: 4, label: '已提交审核' },
        { value: 5, label: '已收入成品库' },
        { value: 6, label: '产品分发中' },
      ],
      contentType: [
        { value: 1, label: '图文' },
        { value: 2, label: '视频' },
        { value: 3, label: '音频' },
        { value: 4, label: '动漫' },
        { value: 5, label: '挂图' },
      ],
      status: [
        { value: 1, label: '待审核' },
        { value: 2, label: '审核中' },
        { value: 3, label: '审核通过' },
        { value: 4, label: '审核未通过' },
        { value: 5, label: '拒绝审核' },
      ],
      protos: [
        { value: 1, label: '原创' },
        { value: 2, label: '网络' },
        { value: 3, label: '委托' },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [{
          required: true,
          message: '手机号格式错误',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        name: [
          { required: true, message: "被邀请人姓名必须填写", trigger: "blur" }
        ],
        job: [
          { required: true, message: "被邀请人职称必须填写", trigger: "blur" }
        ]
        // userId: [
        //   { required: true, message: "操作人ID不能为空", trigger: "blur" }
        // ],
        // userName: [
        //   { required: true, message: "操作人姓名不能为空", trigger: "blur" }
        // ],
        // createTime: [
        //   { required: true, message: "创建时间不能为空", trigger: "blur" }
        // ],
      },
      topList: {
        title: '流程指引',
        list: [
          { name: '素材管理', img: 'blue' },
          { name: '内容创作', img: 'blue' },
          { name: '专家审核', img: 'gray' },
          { name: '产品分发', img: 'gray' },
          { name: '传播管理', img: 'gray' },
        ]
      },
      // proList:[]     //专家列表
      //1：主任医师 2：副主任 3：主任医师
      proDic: [
        { value: 1, label: '主任医师' },
        { value: 2, label: '副主任' },
        { value: 3, label: '主任医师' },
      ],
      tableData: [{
        id: '2016-05-02',
        name: '王小虎',
        doc: '上海市普陀区金沙江路 1518 弄'
      }],
      currentRowData: [],   //点击当前行的信息
      shareUrl: process.env.VUE_APP_BASEURL + `/login`,
      isFirstIn: true,
      priviewInner: []
    }
  },
  created() {
    //console.log(this.shareUrl,'1111');
    this.init()
    this.getList();
  },
  watch: {
    openTiShen(ne, ol) {
      if (!ne) this.currentRowData = []   //关闭diago清空点击当前行信息
      this.isFirstIn = true           //关闭重置点击二维码状态
    }
  },
  methods: {
    updatePre(val) {
      this.preOpen = val
    },
    async preData(data) {
      let res = await ArticlePreview(data)
      this.priviewInner = res.data
      this.preOpen = true
      // console.log(this.priviewInner,'12111');
    },

    preview(row) {
      //console.log(row);
      this.myRow = row
      this.preOpen = true
      //  this.preData({articleTopicId:row.topicId})
      // console.log(row);
    },
    async init() {
      //console.log(encodeURIComponent('http://www.baidu.com'),1233)
      this.invation.url = this.shareUrl

      //image.onload = function () {

      // };

      //console.log(res);
    },
    async makeQr() {
      if (this.isFirstIn) {
        this.isFirstIn = false
      } else {
        return
      }
      let res = await generateArticleQR({ url: this.shareUrl })
      let image = new Image();
      image.src = "data:image/png;base64," + res
      image.width = 200
      image.height = 200
      //console.log(this.$refs.qrimg);
      this.$refs.qrimg.appendChild(image);
    },
    async postData(params) {
      let res = await submitArticleAudit(params)
      //console.log(res, '11111');
      if (res.code == 200) {
        this.$notify.success({
          title: '消息',
          message: res.msg
        })
        this.openTiShen = false
        this.getList();
      }
    },
    async submitData(whichType) {
      if (Object.keys(this.currentRowData).length === 0) return
      const myType = this.contentType.find(v => v.label == this.currentRowData.type)
      const params = {
        // auditType: 1,    //	审核类型 1、指定审核 2、邀请审核 3、内容免审
        contentId: this.currentRowData.articleId,  //内容id
        contentType: myType.value,  //内容类型：1：图文内容，2：素材管理
        // examineUserid: null,  //审核人员id 指定审核、邀请审核必填

      }
      if (whichType == 'zhiding') {  //指定审核
        params.auditType = 1
        params.examineUserid = this.pop.title  //审核人员id 指定审核、邀请审核必填
        // console.log(params);
        // return
        this.postData(params)
        return
      }
      if (whichType == 'yaoqing') {  //邀请审核
        params.auditType = 2
        //params.examineUserid: null,  //审核人员id 指定审核、邀请审核必填
        params.jobTitle = this.invation.job      //被邀请人职称 2、邀请审核填写
        params.mobilePhone = this.invation.phone    //被邀请人电话 2、邀请审核填写
        params.name = this.invation.name          //被邀请人姓名 2、邀请审核填写
        //校验input
        this.$refs['invationForm'].validate(valid => {
          if (!valid) return
          //console.log(1111188,params);
          this.postData(params)
          // TODO 提交表单
        })

        // console.log(params,1111);
        return

      }
      if (whichType == 'free') {   //免审核
        params.auditType = 3
        // params.examineUserid: null,  //审核人员id 指定审核、邀请审核必填
        this.postData(params)
        // console.log(res,'iiiii');
        return
      }
    },
    rowSelect(row, column, event) {
      let rowID = row.userId
      const hasSelected = this.pop.title.includes(rowID)
      // if (!hasSelected) this.pop.title.push(rowID)
      if (!hasSelected) this.pop.title = rowID
      // console.log(row,'row');
    },
    handleClick(tab, event) {  //切换
      //  console.log(tab, event);
    },
    handleExam(row) {  //提审
      this.currentRowData = row
      this.openTiShen = true
      this.getUserList()

      // console.log(123);
    },
    proSearch() {  //点击搜索，模糊查询
      this.getUserList({ name: this.pop.search })
    },
    async getUserList(name) {
      this.options = []   //先清空
      let res = await getAuditStaff(name)
      this.tableData = res.data.map(v => {
        v.id = v.showUserId   //id
        let myType = this.proDic.find(params => params.value == v.type)
        if (myType !== undefined) v.doc = myType.label   //doc
        this.options.push({ 'value': v.userId, 'label': v.name })
        return v
      })
      //console.log(res,1111);
    },
    goEdit() {
      this.$router.push({ path: 'xuanti_edit' })
    },
    /** 查询文章选题列表 */
    getList() {
      this.loading = false;
      chugaoList(this.queryParams).then(response => {
        response.rows.map(v => {
          let typeFind = this.contentType.find(values => values.value == v.type)
          if (typeFind !== undefined) {  //内容类型
            v.type = typeFind.label
          }
          let statusFind = this.status.find(r => r.value == v.articleExamineState)
          if (statusFind !== undefined) {  //审核状态
            v.articleExamineState = statusFind.label
          }
          let protosFind = this.protos.find(params => params.value == v.copyrightType)
          if (protosFind !== undefined) {
            v.copyrightType = protosFind.label
          }
          v.target = this.$cutString(v.target, 8)
          // v.examineFailedReason = this.$cutString(v.examineFailedReason, 8)
          v.digest = this.$cutString(v.digest, 8)
          v.target = this.$cutString(v.target, 8)
          v.title = this.$cutString(v.title, 8)
          return v
          // console.log(v);

        })
        this.topicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        topicId: null,
        topicXh: null,
        keyword: null,
        target: null,
        digest: null,
        outline: null,
        results: null,
        type: null,
        schedule: null,
        userId: null,
        userName: null,
        isDelete: null,
        createTime: null,
        updateTime: null,
        sourceMaterialId: null,
        startTime: null,
        endTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.topicId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增文章选题";
      this.$router.push({ path: '/content/xuanti_edit', 'query': { 'type': 1 } })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      // const topicId = row.topicId || this.ids
      // getTopic(topicId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改文章选题";
      // });
      // console.log(row);
      // return
      this.$router.push({ path: '/content/edit_content', query: { 'type': 2, 'articleId': row.articleId, 'topicId': row.topicId } })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.topicId != null) {
            updateTopic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTopic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleId = row.articleId || row.topicId || this.ids;
      this.$modal.confirm('是否确认删除内容编号为"' + row.topicXh + '"的数据项？').then(function () {
        // return delTopic(topicIds);
        return delMytopicChuGao(articleId)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/topic/export', {
        ...this.queryParams
      }, `topic_${new Date().getTime()}.xlsx`)
    }
  },

}
</script>

<style lang='scss' scoped>
.maina {
  background-color: #f5f5f5;

  .content {
    margin-top: 10px;
    background-color: white !important;

    .content_box {
      padding-left: 32px;

      .title_left {

        padding-top: 31px;
        font-size: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 700;
        color: #3D3D3D;
        line-height: 21px;
      }
    }
  }
}
</style>